import {Card, Button, Form, Input, message, Space, InputNumber} from 'antd'
import { useStore } from '@/store'
import { useState, useEffect } from 'react'
import {useNavigate, useSearchParams} from 'react-router-dom'
import { observer } from 'mobx-react-lite'

const { TextArea } = Input;

const MarkPapers = (props) => {
    const [params] = useSearchParams()
    const id = params.get("id")
    const api = "mark_papers"
    const { operateStore } = useStore()
    const [items, setItems] = useState() //保存考试信息
    const [questions, setQuestions] = useState() 
    const [form] = Form.useForm()
    const navigate = useNavigate()

  
    const onFinish = async(value) => {
        let score = 0
        for(var key in value){
            score = score + value[key]
        }
        console.log(value, score)
        await operateStore.createItem(api, {"score": score, "student_exam_id": items.id})
        message.success("提交成功！")
        navigate(`/list/student_score`)
    }


    useEffect(() => {
        const loadDetail = async () => {
            const data = await operateStore.getDetails(api, id)
            setItems(data)
            setQuestions(data.questions)
        }
        loadDetail()
      }, [api, id, operateStore])
    
    return (
        <div>
            {questions && questions.length > 0 && (
                <Card>
                    <Form
                        form={form}
                        layout="vertical"
                        onFinish={onFinish}
                    >
                        {questions.map(data => {
                            return <><Form.Item label={data.no + "." + data.subject+"("+data.score+"分)"} key={"answer"+data.no}>
                                        <TextArea defaultValue={data.answer} disabled="true" />
                                    </Form.Item>
                                    <Form.Item 
                                        label="分数" 
                                        name={data.no} 
                                        key={data.no}
                                    >
                                     <InputNumber type={'number'} min={0} max={data.score} /> 
                                    </Form.Item></>

                        })}
                        <Form.Item>
                            <Space>
                                <Button size="middle" type="primary" htmlType="submit">保存</Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Card>
            )}
        </div>
    )
} 

export default observer(MarkPapers)